<template>
  <el-button style="margin-bottom: 10px" type="primary" @click="handleAdd"
    >添加新地址</el-button
  >

  <div>
    <tableBody
      ref="table"
      :tableConfig="tableConfig"
      :queryApi="queryApi"
      :isOperate="true"
      :operateWidth="220"
    >
      <template v-slot:operate="slotProps">
        <el-button
          size="small"
          type="warning"
          @click="handleUpd(slotProps.scope.row)"
          >修改</el-button
        >
        <el-button
          size="small"
          type="danger"
          @click="handleDel(slotProps.scope.row)"
          >删除</el-button
        >
        <el-button
          size="small"
          type="primary"
          @click="saveDef(slotProps.scope.row)"
          >设为默认</el-button
        >
      </template>
    </tableBody>

    <el-dialog width="40%" v-model="formVisible" :title="updFormTitle" center>
      <el-form :model="formData" label-width="100px">
        <el-form-item label="收货人">
          <el-input v-model="formData.receiver"></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="formData.phoneno"></el-input>
        </el-form-item>

        <el-form-item
          v-for="(item, index) in listAll"
          :key="item.fieId"
          :label="item.label"
        >
          <el-select
            v-model="formData[item.fieId]"
            placeholder="请选择"
            style="width: 240px"
          >
            <el-option
              v-for="item1 in item.list"
              :key="item1.ssqid"
              :label="item1.ssqname"
              :value="item1.ssqname"
              @click="changeAds(item1, index)"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="详细地址">
          <el-input v-model="formData.details"></el-input>
        </el-form-item>
        <el-form-item>
          <div class="btns">
            <el-button @click="formVisible = false">取消</el-button>
            <el-button type="primary" @click="saveForm"> 确定 </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import tableList from "@/utils/tableBody";
import tableBody from "@/components/tableBody.vue";
import { onMounted, reactive, ref, computed } from "vue";
import { addAddress, updAddress, delAddress, updDefault } from "@/api/address";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "vuex";
import { CODE } from "@/utils/StatusCode";

const queryApi = ref("/address/getAddressPage");
const tableConfig = reactive(tableList.addressList);
const store = useStore();

const userInfo = computed(() => {
  return store.getters.getUserInfo;
});

// 获取省市县数据
const json = require("@/utils/data.json");
interface ssq {
  ssqid: string;
  ssqname: string;
  cities?: {
    city: ssq[];
  };
  areas?: {
    area: ssq[];
  };
}
interface listAll {
  label: string;
  fieId: string;
  list: ssq[];
}
const listAll = ref<listAll[]>([
  {
    label: "省份",
    fieId: "province",
    list: [],
  },
  {
    label: "城市",
    fieId: "city",
    list: [],
  },
  {
    label: "区/县",
    fieId: "county",
    list: [],
  },
]);

onMounted(() => {
  query({ userid: userInfo.value.userid });
  listAll.value[0].list = json.provinces.province;
});
const table = ref(null);
function query(data: any) {
  (table as any).value.onSearch(data);
}

const formVisible = ref(false);

const formData = reactive({
  addressid: "",
  userid: "",
  receiver: "",
  phoneno: "",
  province: "",
  city: "",
  county: "",
  details: "",
  isdefault: 2,
});

function changeAds(data: any, level: number) {
  if (level == 0) {
    listAll.value[1].list = data.cities.city;
    listAll.value[2].list = [];
    formData.city = "";
    formData.county = "";
  } else if (level == 1) {
    listAll.value[2].list = data.areas.area;
    formData.county = "";
  }
}

let updFormTitle = "";

// 修改
function handleUpd(row: any) {
  Object.keys(formData).forEach((fieId) => {
    formData[fieId] = row[fieId];
  });

  formVisible.value = true;
  updFormTitle = "修改地址";
  echoAddress(formData.province, formData.city);
}
// 回显地址
function echoAddress(province: string, city: string) {
  const provinceVal = listAll.value[0].list.find((val) => {
    return val.ssqname == province;
  });
  if (provinceVal?.cities) {
    listAll.value[1].list = provinceVal.cities.city;
    const cityVal = provinceVal.cities.city.find((val) => {
      return val.ssqname == city;
    });
    if (cityVal?.areas) {
      listAll.value[2].list = cityVal.areas.area;
    }
  }
}
// 清空表单
function resetForm() {
  Object.keys(formData).forEach((fieId) => {
    formData[fieId] = "";
  });
}
// 新增
function handleAdd() {
  resetForm();
  formVisible.value = true;
  updFormTitle = "新增商品";
}
// 保存
async function saveForm() {
  let res;
  if (formData.addressid) {
    res = await updAddress(formData);
  } else {
    formData.userid = userInfo.value.userid;
    formData.isdefault = 2;
    res = await addAddress(formData);
  }
  if (res.code == CODE.OK) {
    formVisible.value = false;
  }
  prompt(res);
}
function handleDel(row: any) {
  if (!row.addressid) return;
  ElMessageBox.confirm("是否删除此地址", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await delAddress({
        addressid: row.addressid,
      });
      prompt(res);
    })
    .catch(() => {});
}
// 设为默认
function saveDef(row: any) {
  if (!row.addressid) return;
  ElMessageBox.confirm("是否将此地址设为默认", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await updDefault({
        addressid: row.addressid,
        userid: userInfo.value.userid,
      });
      prompt(res);
    })
    .catch(() => {});
}
function prompt(res: any) {
  if (res.code == CODE.OK) {
    ElMessage({
      message: res.message,
      type: "success",
    });
    query({ userid: userInfo.value.userid });
  } else {
    ElMessage({
      message: res.message,
      type: "error",
    });
  }
}
</script>

<style lang="less" scoped></style>
